'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {
  async info() {
    const { ctx } = this;
    if (ctx.isAuthenticated()) {
      const user = await this.service.user.find(ctx.user.id);
      if (user) {
        const { id, username, name, avatar, introduction, roles } = user;
        ctx.body = { id, username, name, avatar, introduction, roles };
      } else {
        ctx.body = {};
      }
    } else {
      ctx.body = {};
    }
  }

  async register() {
    const { ctx } = this;
    const { username, password, roles } = ctx.request.body;
    const user = await this.service.user.create({ username, password, roles });
    ctx.body = { id: user.id, username: user.username };
  }

  async logout() {
    const { ctx } = this;
    ctx.logout();
    ctx.redirect(ctx.get('referer') || '/');
  }
}

module.exports = UserController;
